package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length < 3) {
			System.out.println("Error, Missing parameters.");
			return;
		}

		String host;
		int tcpPort = 0;
		int udpPort = 0;

		host = args[0];
		try {
			tcpPort = Integer.parseInt(args[1]);
			udpPort = Integer.parseInt(args[2]);
		} catch (NumberFormatException e) {
			System.out.println("Error, invalid port number.");
			return;
		}

		Socket serverSocket;
		DatagramSocket udpSocket;
		try {
			serverSocket = new Socket(host, tcpPort);
			//udpSocket = new DatagramSocket(udpPort);
			
			//ClientUdpReceiverThread udpReceiver = new ClientUdpReceiverThread(udpSocket);
			ClientTcpReceiverThread tcpReceiver = new ClientTcpReceiverThread(serverSocket);
			
			//(new Thread(udpReceiver)).start();
			(new Thread(tcpReceiver)).start();
			
			PrintWriter out = new PrintWriter(serverSocket.getOutputStream(),
					true);
			//BufferedReader in = new BufferedReader(new InputStreamReader(
				//	serverSocket.getInputStream()));

			BufferedReader stdIn = new BufferedReader(new InputStreamReader(
					System.in));
			//String fromServer;
			String fromUser;
			
			String username;

			fromUser = stdIn.readLine();
			while (!"exit".equals(fromUser)) {
				
				if (fromUser != null) {
					
					if (fromUser.startsWith("!login")) {
						String[] splt = fromUser.split(" ");
						username = splt[1];
						//udpReceiver.setUsername(username);
						fromUser = fromUser + " " + udpPort;
					} else if (fromUser.equals("!logout")) {
						username = null;
						//udpReceiver.setUsername(null);
					}
					
					out.println(fromUser);
					/*fromServer = in.readLine();
					if (fromUser.equals("!list")) {
						System.out.println(fromServer.replace("|", "\r\n"));
					} else {
						System.out.println(fromServer);
					}*/
				}
				fromUser = stdIn.readLine();
			}
			
			out.close();
	        //in.close();
	        stdIn.close();
	        serverSocket.close();
	        //udpReceiver.setRunning(false);
	        //udpSocket.close();
		} catch (UnknownHostException e) {
			System.out.println("Couldn't find server " + host);
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
